<template>
  <div class="login-container">
    <div class="login-form">
      <div class="login-header">
        <h2>用户登录</h2>
      </div>
      <!-- 步骤一：序列号校验 -->
      <el-form
        v-if="isFirstLaunch"
        ref="serialFormRef"
        :model="serialForm"
        class="login-form-content"
        @keyup.enter="handleSerialLogin"
        :rules="serialRules"
      >
        <el-form-item label="序列号" prop="xulieh">
          <el-input
            v-model="serialForm.xulieh"
            placeholder="请输入序列号"
            size="large"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            size="large"
            style="width: 100%"
            @click="handleSerialLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 步骤二：账号密码登录 -->
      <el-form
        v-else
        ref="loginFormRef"
        :model="loginForm"
        class="login-form-content"
        @keyup.enter="handleLogin"
        :rules="loginRules"
      >
        <el-form-item label="账号" prop="dl_zhanghao">
          <el-input
            v-model="loginForm.dl_zhanghao"
            placeholder="请输入账号"
            size="large"
          />
        </el-form-item>
        <el-form-item label="密码" prop="dl_mima">
          <el-input
            v-model="loginForm.dl_mima"
            type="password"
            placeholder="请输入密码"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            size="large"
            style="width: 100%"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
        <div style="display: flex; justify-content: space-between; margin-top: 10px;">
          <el-link type="info" @click="handleForgot">忘记密码</el-link>
          <el-link type="info" @click="handleLogoff">注销账号</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import md5 from 'js-md5'
import { Base64 } from 'js-base64'
import axios from 'axios'
import request, { serialVerifyService, getApiPath } from '@/utils/request'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const isFirstLaunch = ref(!localStorage.getItem('hasLaunched'))
    
    // 表单数据
    const serialForm = ref({ xulieh: '' })
    const loginForm = ref({ dl_zhanghao: '', dl_mima: '' })
    
    // 表单验证规则
    const serialRules = reactive({
      xulieh: [{ required: true, message: '请输入序列号', trigger: 'blur' }]
    })
    
    const loginRules = reactive({
      dl_zhanghao: [{ required: true, message: '请输入账号', trigger: 'blur' }],
      dl_mima: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    })
    
    // 表单引用
    const serialFormRef = ref()
    const loginFormRef = ref()

    // 序列号校验
    const handleSerialLogin = async () => {
      serialFormRef.value.validate(async (valid) => {
        if (!valid) return
        loading.value = true
        const xulieh = serialForm.value.xulieh
        const shijian = new Date().getTime()
        const miwen = md5(xulieh + 'sshc' + shijian)
        const bs64_cs = { xulieh, shijian, miwen }
        const cs = {
          ctype: 'zlxt_3_shujuk_bdym',
          bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
          bs64_obj: '',
          bs64_list: '',
          ids: ''
        }
        try {
          // 使用序列号校验专用服务
          const res = await serialVerifyService.post('/xcx/ajax/Ajax_xcxpost.ashx', { canshu: cs })
          // console.log('序列号校验响应:', res);
          
          // 修复判断逻辑，检查各种可能的响应格式
          if (res && (res.leixing === 'ok' || (res.data && res.data.leixing === 'ok'))) {
            // 兼容两种可能的响应格式
            const data = res.leixing === 'ok' ? res : res.data;
            localStorage.setItem('yuming', data.yuming || '')
            localStorage.setItem('xulieh', xulieh)
            localStorage.setItem('hasLaunched', 'true')
            isFirstLaunch.value = false
            ElMessage.success('序列号校验成功，请登录账号')
          } else {
            // 错误信息也兼容两种格式
            const errorMsg = (res.leixing === 'error' && res.msg) || 
                            (res.data && res.data.leixing === 'error' && res.data.msg) || 
                            '序列号校验失败';
            ElMessage.error(errorMsg)
          }
        } catch (e) {
          console.log('序列号校验异常:', e);
          ElMessage.error('网络错误，请稍后重试')
        } finally {
          loading.value = false
        }
      })
    }

    // 账号密码登录
    const handleLogin = async () => {
      loginFormRef.value.validate(async (valid) => {
        if (!valid) return
        loading.value = true
        // 使用固定的openid格式，与app端保持一致
        const openid = "17524180246839845722"
        const bs64_cs = {
          openid,
          dl_zhanghao: loginForm.value.dl_zhanghao,
          dl_mima: loginForm.value.dl_mima
        }
        const cs = {
          ctype: 'zlxt_3_user_denglu',
          bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
          bs64_obj: '',
          bs64_list: '',
          ids: ''
        }
        try {
          // 使用统一的请求工具
          const res = await request.post(getApiPath(cs.ctype), { canshu: cs })
          // console.log('账号登录响应:', res);
          
          // 修复判断逻辑，检查各种可能的响应格式
          if (res && (res.leixing === 'ok' || (res.data && res.data.leixing === 'ok'))) {
            // 兼容两种可能的响应格式
            const data = res.leixing === 'ok' ? res : res.data;
            localStorage.setItem('user', JSON.stringify(data))
            // 设置部门编号，优先使用返回的数据，否则使用默认值
            localStorage.setItem('bumenbh', data.bumenbh || data.org_code || '0001')
            ElMessage.success('登录成功')
            // 登录成功后自动获取token
            await getToken(openid)
            router.push('/dashboard')
          } else {
            // 错误信息也兼容两种格式
            const errorMsg = (res.leixing === 'err' && res.msg) ||
                            (res.data && res.data.leixing === 'err' && res.data.msg) ||
                            '账号或密码错误';
            ElMessage.error(errorMsg)
          }
        } catch (e) {
          console.log('登录异常:', e);
          ElMessage.error('网络错误，请稍后重试')
        } finally {
          loading.value = false
        }
      })
    }

    // 获取token方法（与app端一致）
    const getToken = async (openid) => {
      // 保存openid到localStorage，确保其他页面能够使用相同的openid
      localStorage.setItem('openid', openid)
      
      const bs64_cs = {
        cid: 0,
        openid
      }
      const cs = {
        ctype: 'app_gettoken',
        bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
        bs64_obj: '',
        bs64_list: '',
        ids: ''
      }
      try {
        // 使用统一的请求工具
        const res = await request.post(getApiPath(cs.ctype), { canshu: cs })
        // console.log('获取token响应:', res);
        
        // 检查不同的响应格式
        if (res && res.token) {
          localStorage.setItem('token', res.token)
        } else if (res.data && res.data.token) {
          localStorage.setItem('token', res.data.token)
        }
      } catch (e) {
        console.log('获取token异常:', e);
        // token获取失败可忽略
      }
    }

    // 忘记密码
    const handleForgot = () => {
      ElMessage.info('请联系管理员重置密码')
    }

    // 注销账号
    const handleLogoff = async () => {
      const openid = localStorage.getItem('openid') || "17524180246839845722"
      const bs64_cs = { openid }
      const cs = {
        ctype: 'app_tuichu_xitong',
        bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
        bs64_obj: '',
        bs64_list: '',
        ids: ''
      }
      try {
        // 使用统一的请求工具
        const res = await request.post(getApiPath(cs.ctype), { canshu: cs })
        // console.log('注销响应:', res);
        
        // 无论响应如何，都清除本地数据并重新加载页面
        localStorage.clear()
        window.location.reload()
        ElMessage.success('账号已注销')
      } catch (e) {
        console.log('注销异常:', e);
        // 即使出现错误，也要尝试清除本地数据
        localStorage.clear()
        window.location.reload()
        ElMessage.warning('注销过程中出现异常，已清除本地登录信息')
      }
    }

    return {
      isFirstLaunch,
      serialForm,
      loginForm,
      serialFormRef,
      loginFormRef,
      loading,
      serialRules,
      loginRules,
      handleSerialLogin,
      handleLogin,
      handleForgot,
      handleLogoff
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-form {
  width: 400px;
  background: white;
  border-radius: 10px;
  padding: 40px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.login-header p {
  color: #909399;
  margin: 0;
}

.login-form-content {
  margin-top: 20px;
}

.login-tips {
  margin-top: 20px;
  text-align: center;
}

.login-tips p {
  color: #909399;
  font-size: 14px;
  margin: 0;
}
</style>
